<template>
  <div class="flexContent">
    <div class="searchBox">
      <!-- 订单列表 -->
      <el-form class="demo-form-inline" label-position="left" label-width="auto">
        <div class="serFlexBox">
          <div class="inputBox">
            <el-row :gutter="12" style="display: flex;flex-wrap: wrap;">
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="门店">
                  <el-select v-model="sForm.storeId" @click.native="getShopAllList" filterable clearable
                    popper-class="eloption" style="width: 95%">
                    <el-option v-for="shop in shopListTwo" :key="shop.id" :value="shop.id" :label="shop.name" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="状态">
                  <el-select v-model="sForm.entryStatus" filterable clearable popper-class="eloption"
                    style="width: 95%">
                    <el-option value="" label="全部" />
                    <el-option value="0" label="未分录" />
                    <el-option value="1" label="已分录" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="订单状态">
                  <el-select v-model="sForm.status" filterable clearable popper-class="eloption" style="width: 95%">
                    <el-option value="" label="全部" />
                    <el-option value="1" label="待发货" />
                    <el-option value="2" label="已发货" />
                    <el-option value="3" label="已完成" />
                    <!-- <el-option value="4" label="已关闭" /> -->
                    <el-option value="5" label="已退款" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="订单编号">
                  <el-input v-clearEmoji v-model.trim="sForm.tradeNo" placeholder="请输入" size="small" clearable
                    style="width: 95%" @keyup.enter.native="searchFn" />
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="支付方式">
                  <el-select v-model="sForm.payType" filterable clearable popper-class="eloption" style="width: 95%">
                    <el-option value="0" label="微信支付" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="10" :xl="6">
                <el-form-item label="订单时间">
                  <el-date-picker clearable v-model="date" style="width: 95%" type="daterange" unlink-panels
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="btnBox">
            <el-button @click.stop="searchFn" class="searchBtn" icon="el-icon-search">搜索</el-button>
            <el-button @click.stop="resetFn" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <div class="table" id="tableBox" v-height>
      <div style="flex:1;">
        <vxe-table :column-config="{ resizable: true }" border class="tablebox" ref="xTable1"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%" height="100%"
          size="medium" align="center">
          <vxe-column type="seq" width="80" title="序号" />
          <vxe-column field="tradeNo" title="订单编号" :min-width="elTableAdaptationWidth('tradeNo', shopList)" />
          <vxe-column field="storeName" title="门店名称" :min-width="elTableAdaptationWidth('storeName', shopList)" />
          <vxe-column field="receiverName" title="收货人" min-width="150" />
          <vxe-column field="receiverAddress" title="收货地址" min-width="300">
            <template v-slot="{ row }">
              <span>{{ row.receiverRegion }}/{{ row.receiverAddress }}</span>
            </template>
          </vxe-column>
          <vxe-column field="payType" title="支付方式" min-width="120">
            <template v-slot="{ row }">
              <span v-if="row.payType == '0'">微信支付</span>
            </template>
          </vxe-column>
          <vxe-column field="payAmount" title="订单金额（元）" min-width="150" />
          <vxe-column field="createTime" title="订单时间" min-width="150">
            <template v-slot="{ row }">
              <span>{{ row.createTime | parseTime }}</span>
            </template>
          </vxe-column>
          <vxe-column field="entryStatus" title="状态" width="100">
            <template v-slot="{ row }">
              <el-tag v-if="row.entryStatus === '0'" disabled type="info" plain size="small">未分录</el-tag>
              <el-tag v-if="row.entryStatus === '1'" disabled type="primary" plain size="small">已分录</el-tag>
            </template>
          </vxe-column>
          <vxe-column field="status" title="订单状态" width="100" :key="Math.random()">
            <template v-slot="{ row }">
              <el-tag v-if="row.status === '0'" disabled type="info" plain size="small">待付款</el-tag>
              <el-tag v-if="row.status === '1'" disabled type="primary" plain size="small">待发货</el-tag>
              <el-tag v-if="row.status === '2'" disabled type="primary" plain size="small">已发货</el-tag>
              <el-tag v-if="row.status === '3'" disabled type="primary" plain size="small">已完成</el-tag>
              <el-tag v-if="row.status === '4'" disabled type="primary" plain size="small">已关闭</el-tag>
              <el-tag v-if="row.status === '5'" disabled type="primary" plain size="small">已退款</el-tag>
            </template>
          </vxe-column>
          <vxe-column v-if="$showFn(['shoporder_detail', 'deliver_goods', 'refund'])" fixed="right" width="150"
            title="操作">
            <template v-slot="{ row }">
              <el-button type="text" v-has="'shoporder_detail'" style="margin-right: 10px; color: rgb(0, 132, 255)"
                @click.stop="shopDetail(row)">详情</el-button>
              <el-button style="color: rgb(0, 132, 255)" type="text" v-has="'deliver_goods'"
                v-if="row.status === '1' && row.entryStatus === '1'" @click.stop="shipmentsGoods(row)">发货</el-button>
              <el-button style="color: rgb(0, 132, 255)" type="text" v-has="'refund'"
                @click.stop="rebatesFn(row)">退款</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="paginationBox">
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total,-> , sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-dialog title="发货" :visible.sync="dialogVisible" width="40%" @close="btnClose">
      <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="100px">
        <el-form-item label="配送方式" style="width: 100%" prop="deliveryType">
          <el-select v-model="addForm.deliveryType" filterable clearable popper-class="eloption" style="width: 70%">
            <el-option value="1" label="物流快递" />
            <el-option value="2" label="同城配送" />
            <el-option value="3" label="虚拟发货" />
            <el-option value="4" label="用户自提" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="addForm.deliveryType == '1'" label="物流公司" style="width: 100%" prop="deliveryId">
          <el-select v-model="addForm.deliveryId" @change="deliveryCompanyFn" @click.native="getLogisticsInfo"
            filterable clearable popper-class="eloption" style="width: 70%">
            <el-option v-for="item in logisticsInfo" :key="item.id" :value="item.code" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="addForm.deliveryType == '1'" label="物流单号" style="width: 100%" prop="deliverySn">
          <el-input v-model="addForm.deliverySn" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button class="celBtn" @click="btnClose">取 消</el-button>
        <el-button class="addBtn" @click="btnOk">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 退款窗口 -->
    <el-drawer title="退货详情" :visible.sync="drawer" size="60%" @close="cancelFn">
      <div class="drawertable">
        <div class="rows">
          <!-- <span style="color: red">*</span> -->
          <span class="col">订单编号：{{ tradeNo }}</span>
          <span class="col">收货电话：{{ receiverPhone }}</span>
          <span class="col">订单金额：{{ payAmount }}</span>

        </div>
        <div class="rows">
          <span class="col">门店名称：{{ storeName }}</span>
          <span class="col">订单地址：{{ receiverRegion }}/{{ receiverAddress }}</span>
          <span class="col" v-if="entryStatus == '0' && status != '5'">订单状态：待分录</span>
          <span class="col" v-if="status == '0' && entryStatus == '1'">订单状态：待付款</span>
          <span class="col" v-if="status == '1' && entryStatus == '1'">订单状态：待发货</span>
          <span class="col" v-if="status == '2' && entryStatus == '1'">订单状态：已发货</span>
          <span class="col" v-if="status == '3' && entryStatus == '1'">订单状态：已完成</span>
          <span class="col" v-if="status == '4' && entryStatus == '1'">订单状态：已关闭</span>
          <span class="col" v-if="status == '5'">订单状态：已退款</span>

        </div>
        <div>
          <el-form ref="formData" @submit.native.prevent :model="diaForm" :rules="diaRules">
            <el-table border class="tablebox" :max-height="475" ref="multipleTable" :data="diaForm.tableData"
              @selection-change="selFn" size="medium">
              <el-table-column type="selection" align="center" width="55" />
              <el-table-column label="商品名称" prop="commodityName" align="center" />
              <el-table-column align="center" label="购买数量" prop="count" />
              <el-table-column align="center" label="已退数量" prop="refundedCount" />
              <el-table-column align="center" label="可退数量" prop="canRefunds" />
              <el-table-column align="center" label="退货数量" prop="refundQuantity">
                <template slot-scope="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.refundQuantity'"
                    :rules="diaRules.refundQuantity">
                    <el-input v-clearEmoji ref="inputaldQty" @blur="numberChange(scope.row, scope.$index)"
                      v-model.number="scope.row.refundQuantity" placeholder="" class="group-inp" size="small"
                      style="width: 100%" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="总价（元）" prop="total" />
            </el-table>
          </el-form>
        </div>
      </div>
      <div class="btnBOX">
        <el-button class="celBtn" @click="cancelFn" style="margin-right: 50px;">取 消</el-button>
        <el-button class="addBtn" @click="submitForm" v-has="'agreement_add'">确 定</el-button>
      </div>
    </el-drawer>
    <el-dialog title="退款原因" :visible.sync="dialogVisible2" width="30%" @close="closeFn">
      <el-input v-clearEmoji type="textarea" :rows="5" placeholder="请输入退款原因" maxlength="100" v-model.trim="remark"
        style="width: 100%;"></el-input>
      <span slot="footer">
        <el-button class="celBtn" @click="closeFn">取 消</el-button>
        <el-button class="addBtn" @click="updateShopStatus">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getShopOrderList, getShopAllList, confirmOrderInfo, orderDelivery, getLogisticsInfo } from "@/api/shopManagement";
import { getRefundOrderDetail, shopOrderReturn } from "@/api/shopManagement";
export default {
  name: "GoodsInfo",
  data() {
    return {
      drawer: false,
      dialogVisible: false,
      dialogVisible2: false,
      remark: '', // 拒绝原因
      shop: {},
      sForm: {
        storeId: '',
        entryStatus: '',
        payType: '',
        endTime: '',
        openTime: '',
        status: '',
        tradeNo: ''
      },
      addForm: {
        deliveryType: '',
        deliveryCompany: '',
        deliveryId: '',
        deliverySn: ''
      },
      addRules: {
        deliveryType: [{
          required: true,
          message: '请选择配送方式',
          trigger: 'change'
        }],
        deliverySn: [{
          required: true,
          message: '请输入物流单号',
          trigger: 'blur'
        }, {
          min: 1,
          max: 20,
          message: '物流单号长度在 1 到 20 个字符',
          trigger: 'blur'
        }, {
          validator: (rule, value, callback) => {
            if (/^[a-zA-Z0-9]+$/.test(value) === false) {
              callback(new Error('物流单号只能为数字和字母'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        deliveryId: [{
          required: true,
          message: '请选择物流公司',
          trigger: 'blur'
        }]
      },
      shopList: [],
      shopListTwo: [],
      logisticsInfo: [],
      date: [],
      isSearch: false,
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      name: "",
      orderId: '',
      // tableData: [],
      diaForm: {
        tableData: [],
      },
      diaRules: {
        refundQuantity: [
          {
            required: true,
            message: "请输入退货数量",
            trigger: "blur",
          },
          {
            pattern: /^\+?[1-9]\d*$/,
            message: "退货数量必须是正整数",
            trigger: "blur",
          }
        ]
      },

      tradeNo: "",
      receiverPhone: "",
      payAmount: "",
      storeName: "",
      receiverAddress: "",
      receiverRegion: '',
      status: null,
      entryStatus: '',
      payType: '',
      receiverName: null,
      paymentTime: null,

      detailsList: [],
      orderId: '',
      orderdetailsList: []
    };
  },
  created() {
    this.getShopOrderList();
    this.getShopAllList();
    this.getLogisticsInfo();
  },
  methods: {
    async getShopOrderList() {
      if (!this.isSearch) {
        this.sForm = {
          storeId: '',
          entryStatus: '',
          payType: '',
          endTime: '',
          openTime: '',
          status: '',
          tradeNo: ''
        }
      }
      const res = await getShopOrderList({
        ...this.page,
        ...this.sForm
      });
      if (res.code === 200) {
        console.log(res);
        const result = res.data;
        this.shopList = result.list;
        this.page.pageSize = result.pageSize;
        this.page.pageNum = result.pageNum;
        this.page.total = result.total;
        console.log("shopList", this.shopList);
        const $table = this.$refs.xTable1
        $table.loadData(this.shopList);
      } else {
        // this.$message.error(res.message);
      }
    },
    async getShopAllList() {
      const res = await getShopAllList()
      if (res.code === 200) {
        this.shopListTwo = res.data
      }
    },
    // 获取物流类型
    async getLogisticsInfo() {
      const res = await getLogisticsInfo()
      if (res.code === 200) {
        this.logisticsInfo = res.data
        console.log('物流', res.data);
      }
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      console.log(`每页 ${val} 条`);
      this.getShopOrderList();
    },
    // 获取页数改变
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page.pageNum = val;
      this.getShopOrderList();
    },
    shopDetail(row) {
      this.$router.push({
        path: "shopOrderDetail",
        query: {
          id: row.id,
        },
      });

    },
    async shipmentsGoods(row) {
      // 调接口判断是否有非标商品
      console.log('id', row.id);
      this.orderId = row.id
      const res = await confirmOrderInfo({ id: row.id })
      if (res.code === 200) {
        console.log('res', res);
        if (!res.data) {
          this.dialogVisible = true
        } else {
          this.$confirm('当前订单包含非标商品，请确认非标商品是否发货。', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            this.dialogVisible = true
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消发货'
            });
          });
        }
      }
      // this.shop = row
    },
    async searchFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.sForm.openTime = this.date?.length ? this.date[0] : "";
      this.sForm.endTime = this.date?.length ? this.date[1] : "";
      this.isSearch = true;
      this.getShopOrderList();
    },
    resetFn() {
      this.sForm = {
        storeId: '',
        entryStatus: '',
        payType: '',
        endTime: '',
        openTime: '',
        status: '',
        tradeNo: ''
      }
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.date = []
      this.isSearch = false;
      this.getShopOrderList();
    },
    btnClose() {
      this.$refs.addFormRef.resetFields();
      this.dialogVisible = false
      this.shop = {}
      this.addForm = {
        deliveryType: '',
        deliveryCompany: '',
        deliverySn: ''
      }
    },
    async btnOk() {
      console.log('发货');
      if (this.addForm.deliveryType != '1') {
        this.addForm.deliveryCompany = null
        this.addForm.deliverySn = null
        this.addForm.deliveryId = null
      }
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          console.log('form', this.addForm);
          const res = await orderDelivery({
            ...this.addForm,
            id: this.orderId
          })
          if (res.code === 200) {
            this.$message.success('发货成功')
            this.dialogVisible = false
            this.getShopOrderList();
            this.btnClose()
          }
        }
      })

    },
    deliveryCompanyFn(val) {
      console.log('11', val);
      if (val) {

        const i = this.logisticsInfo.findIndex(item => item.code === val)
        this.addForm.deliveryCompany = this.logisticsInfo[i].name
        console.log('form', this.addForm);
      } else {
        this.addForm.deliveryCompany = null
      }
    },
    async rebatesFn(row) {
      this.drawer = true
      this.orderId = row.id
      const res = await getRefundOrderDetail({ orderId: row.id });
      if (res.code === 200) {
        // this.diaForm.tableData = res.data.detailsList;
        this.tradeNo = res.data.tradeNo;
        this.receiverPhone = res.data.receiverPhone;
        this.payAmount = res.data.payAmount;
        this.storeName = res.data.storeName;
        this.receiverAddress = res.data.receiverAddress;
        this.receiverRegion = res.data.receiverRegion;
        this.status = res.data.status;
        this.payType = res.data.payType;
        this.entryStatus = res.data.entryStatus;
        this.receiverName = res.data.receiverName;
        this.paymentTime = res.data.paymentTime;
        this.diaForm.tableData = res.data.detailsList.map(item => {
          return {
            ...item,
            refundQuantity: item.canRefunds
          }
        })
      }
    },
    async selFn(selection) {
      this.detailsList = []
      console.log(selection, 'selection')
      this.detailsList = selection.map(item => item.id)
      console.log('this.detailsList', this.detailsList);
    },
    cancelFn() {
      this.remark = ''
      this.orderdetailsList = []
      this.diaForm.tableData = []
      this.detailsList = []
      this.drawer = false
    },
    async submitForm() {
      this.orderdetailsList = []
      this.diaForm.tableData.forEach(item => {
        if (this.detailsList.includes(item.id)) {
          this.orderdetailsList.push({
            refundQuantity: item.refundQuantity,
            orderDetailsId: item.id
          })
        }
      }
      )
      if (this.orderdetailsList.length === 0) {
        return this.$message.warning('请选择退货商品')
      }
      let l = 0
      this.orderdetailsList.forEach(item => {
        if (!item.refundQuantity || item.refundQuantity <= 0) {
          l++
        }
      })
      if (l > 0) return this.$message.warning('请输入退货数量')
      console.log('点击退货', this.orderId, this.orderdetailsList);
      // return
      this.dialogVisible2 = true

    },
    numberChange(row, index) {
      const refundQuantity = row.refundQuantity;
      const canRefunds = row.canRefunds;
      // 判断退货数量不能大于可退数量
      if (refundQuantity > canRefunds) {
        this.$message.warning("退货数量不能大于可退数量");
        this.$set(this.diaForm.tableData[index], "refundQuantity", canRefunds);
      }
    },
    async updateShopStatus() {
      if (!this.remark) {
        return this.$message.warning('请输入退货原因')
      }
      // return 
      const res = await shopOrderReturn({
        orderId: this.orderId,
        reason: this.remark,
        detailsList: this.orderdetailsList
      })
      if (res.code === 200) {
        this.$message.success('退款成功')
        this.getShopOrderList();
        this.closeFn()
        this.cancelFn()
      }
    },
    closeFn() {
      this.remark = ''
      this.dialogVisible2 = false
    }
  },
};
</script>

<style lang="scss" scoped>
.txtBox {
  padding-left: 20px;
  margin-bottom: 30px;

}

.btnBOX {
  text-align: center;
}

.drawertable {
  padding: 20px;
}

.rows {
  display: flex;
  margin-bottom: 20px;

  .col {
    width: 33%;
  }
}

::v-deep .el-drawer__header {
  span {
    border: none !important;
  }
}

// An highlighted block
.right-pop-box {
  ::v-deep .el-drawer__header {
    span {
      outline: none;
    }
  }
}
</style>
